export default class Window {
  private defaultWidth: number;
  private defaultHeight: number;
  private rate: number;
  private static instance: Window | null = null;
  private static getAppCallback: () => HTMLDivElement;
  private static getMainCallback: () => HTMLDivElement;

  constructor(defaultWidth: number, defaultHeight: number) {
    this.defaultWidth = defaultWidth;
    this.defaultHeight = defaultHeight;
    this.rate = this.defaultWidth / this.defaultHeight;
  }

  public static create(
    defaultWidth: number,
    defaultHeight: number,
    getAppCallback: () => HTMLDivElement,
    getMainCallback: () => HTMLDivElement
  ) {
    Window.getAppCallback = getAppCallback;
    Window.getMainCallback = getMainCallback;
    if (Window.instance == null) {
      Window.instance = new Window(defaultWidth, defaultHeight);
    } else {
      if (
        Window.instance.defaultWidth !== defaultWidth ||
        Window.instance.defaultHeight !== defaultHeight
      ) {
        Window.instance = new Window(defaultHeight, defaultHeight);
      }
    }
  }

  private resize() {
    const clientWidth = window.innerWidth;
    const clientHeight = window.innerHeight;
    const widthRate = window.innerWidth / this.defaultWidth;
    const heightRate = window.innerHeight / this.defaultHeight;
    const rate = window.innerWidth / window.innerHeight;

    // main 是缩放的内容
    const main = Window.getMainCallback();

    if (rate > this.rate) {
      // 缩放 app
      main.style.transform = `scale(${widthRate},${widthRate})`;
      main.style.transformOrigin = "top left";
      main.style.width = this.defaultWidth + "px";
      main.style.height = this.defaultHeight + "px";

      document.body.style.overflowX = "hidden";
      document.body.style.overflowY = "auto";
    } else if (rate < this.rate) {
      // 缩放 app
      main.style.transform = `scale(${heightRate},${heightRate})`;
      main.style.transformOrigin = "top left";
      main.style.width = this.defaultWidth + "px";
      main.style.height = this.defaultHeight + "px";

      document.body.style.overflowX = "auto";
      document.body.style.overflowY = "hidden";
    } else {
      main.style.transform = `scale(${widthRate},${heightRate})`;
      main.style.transformOrigin = "top left";
      main.style.width = this.defaultWidth + "px";
      main.style.height = this.defaultHeight + "px";

      document.body.style.overflow = "hidden";
    }

    // app 用来裁剪 main
    // 为什么需要用一个 app 来裁剪呢？是因为缩小后，缩小的内容会有一个留白区，那个是占据 main 的客户区的。
    // 所以用 app 裁剪掉。
    const app = Window.getAppCallback();
    app.style.width = clientWidth + "px";
    app.style.height = clientHeight + "px";
  }

  public static autoResize() {
    if (Window.instance != null) {
      Window.instance.resize();
    }
  }
}
